import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { avoidTheLogin, getToken, setToken } from '@/utils/auth'
import {asyncRoutes} from '@/router'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/auth-redirect', '/approvalCac']

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const hasToken = getToken();
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasRoles = store.getters.rolearray && store.getters.rolearray.length > 0
      if (hasRoles) {
        next()
      } else {
        try {
          store.dispatch('user/getInfo').then(res => {
            const { aRoleAuthDTO, userCode } = res;
            // store.dispatch('permission/getAuthUserInfo', userCode);
            console.log("==2131==",aRoleAuthDTO);
            store.dispatch('permission/generateRoutes', aRoleAuthDTO).then(accessRoutes => {
              console.log("=====",accessRoutes);
              router.addRoutes(accessRoutes)
              store.dispatch('permission/getUserAuth', userCode).then(res => {
                next({ ...to, replace: true })
              })
            })
          })
        } catch (error) {
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      const avoid = process.env.VUE_APP_BASE_AVOID
      if (avoid) {
        // 厂外跳login页面
        next(`/login?redirect=${to.path}`)
        NProgress.done()
      } else {
        // 厂内环境门户免密登录
        avoidTheLogin().then(res => {
          if (res.code == 200 && res.token) {
            store.dispatch('user/setToken', res.token)
            setToken(res.token)
            next({ path: '/' })
          } else {
            next(`/login?redirect=${to.path}`)
            NProgress.done()
          }
        })
      }
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
